package su.levenetc.ohos.draggableview;

import ohos.agp.components.VelocityDetector;
import ohos.agp.render.Canvas;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.ThreeDimView;
import ohos.agp.utils.Point;
import ohos.app.Context;
import ohos.media.image.PixelMap;

/**
 * Created by Eugene Levenetc.
 */
public class RotateView extends DraggableView {
    protected static final float ROT_MULT = 10f;

    public RotateView(
            Context context,
            PixelMap bitmap,
            VelocityDetector velocityTracker,
            Point selectedViewPoint,
            Point downEventPoint,
            DragController.IDragViewGroup viewGroup) {
        super(
                context,
                bitmap,
                velocityTracker,
                selectedViewPoint,
                downEventPoint,
                viewGroup
        );
    }

    @Override
    protected boolean render(Canvas canvas) {
        float rotY = 0;
        float rotX = 0;

        if (motionEvent != null) {
            velocityVector.addMovement(motionEvent);
            rotY = ROT_MULT * velocityVector.getXVelocity();
            rotX = ROT_MULT * velocityVector.getYVelocity() * -1;
        }

        canvas.save();
        canvas.translate(xCanvasTranslation, yCanvasTranslation);
        final float translateX = bitmap.getImageInfo().size.width / 2;
        final float translateY = bitmap.getImageInfo().size.height / 2;

        camera = new ThreeDimView();

        camera.rotateY(rotY);
        camera.rotateX(rotX);
        camera.getMatrix(cameraMatrix);
        cameraMatrix.preTranslate(-translateX, -translateY);
        cameraMatrix.postTranslate(translateX, translateY);

        canvas.concat(cameraMatrix);
        PixelMapHolder pixelMapHolder = new PixelMapHolder(bitmap);
        canvas.drawPixelMapHolder(pixelMapHolder, 0, 0, paint);
        canvas.restore();

        return !(rotX == 0) || !(rotY == 0);
    }
}
